package com.hmdp.config;

import com.hmdp.interceptor.LoginInterceptor;
import com.hmdp.interceptor.TokenRefreshInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig  implements WebMvcConfigurer {
    @Autowired
    private TokenRefreshInterceptor tokenRefreshInterceptor;
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器，并排除一些特定路径以提高性能
        registry.addInterceptor(loginInterceptor).order(1)
                .excludePathPatterns(
                        "/shop/**",
                        "/voucher/**",
                        "/shop-type/**",
                        "/upload/**",
                        "/blog/hot",
                        "/user/code",
                        "/user/login"
                );
        registry.addInterceptor(tokenRefreshInterceptor).order(0);
    }


    /**
     * 配置并返回一个RedisTemplate实例，用于操作Redis数据库
     * 该方法配置了Key和Value的序列化方式，以确保数据在存储和读取时的一致性和高效性
     *
     * @param factory Redis连接工厂，用于创建与Redis数据库的连接
     * @return 配置好的RedisTemplate实例，用于执行对Redis数据库的操作
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // Key 序列化器（String）
        template.setKeySerializer(new StringRedisSerializer());

        // Value 序列化器（JSON）
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);

        // HashKey/HashValue 序列化器（必须配置！）
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        // 初始化
        template.afterPropertiesSet();

        return template;
    }


}
